#!/usr/bin/python2.4
#
# Copyright 2009 Google Inc.
# 
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# 
#      http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


"""Serves tile images from a tree of zip files.

When you request $URL/a/b/c/d.png (for instance) this looks for
  $ROOT/a.zip, containing a/b/c/d.png
  $ROOT/a/b.zip, containing b/c/d.png
  $ROOT/a/b/c.zip, containing c/d.png
"""

__author__ = "anthonybaxter@gmail.com (Anthony Baxter)"

import os
from google.appengine.ext import webapp
from google.appengine.ext import zipserve
import wsgiref.handlers


class TreeZipHandler(zipserve.ZipHandler):
  """Serves tile images from a tree of zip files.

      When you request $URL/a/b/c/d.png (for instance) this looks for
        $ROOT/a.zip, containing a/b/c/d.png
        $ROOT/a/b.zip, containing b/c/d.png
        $ROOT/a/b/c.zip, containing c/d.png
  """
  # Change this to point to the root of the tree of zips. Must be in the 
  # filesystem, i.e. not served as static files (which are stored in blobstore)
  ziproot = "../zips/tiles"

  def get(self, name):
    """GET handler."""
    #logging.debug("serving %s"%(name))
    path = self.ziproot
    while "/" in name:
      npath, rest = name.split("/", 1)
      path = os.path.join(path, npath)
      zipfile = path + ".zip"
      if os.path.exists(zipfile):
        filename = os.path.join(npath, rest)
        #logging.debug("serving %s from %s"%(filename, zipfile))
        self.ServeFromZipFile(zipfile, filename)
        return
      else:
        pass
        #logging.debug("didnt find %s"%zipfile)
      name = rest
    self.error(404)


def main():
  app = webapp.WSGIApplication([
      ("/zip/tiles/(.*)", TreeZipHandler),
      ], debug=True)
  wsgiref.handlers.CGIHandler().run(app)

if __name__ == "__main__":
  main()
